package alp.starcode.nudtportal.framework.util;

import alp.starcode.common.exception.CustomException;
import alp.starcode.nudtportal.framework.constant.ProjectConst;
import alp.starcode.nudtportal.framework.constant.CodeConst;
import alp.starcode.nudtportal.framework.login.user.User;
import cn.dev33.satoken.context.SaHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RequestHolder {

    @Autowired
    private RedisUserUtil redisUserUtil;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 在请求开始时添加
     */
    public void add(User user) {
        String key = ProjectConst.USER_PREFIX + SaHolder.getRequest().getHeader(ProjectConst.ID_TOKEN);
        redisTemplate.opsForValue().set(key, user, 30, TimeUnit.MINUTES); // 设置过期时间为30分钟
    }


    /**
     * 获取当前请求的用户对象
     */
    public  User getCurrentLoginCASUser() {
        String key = ProjectConst.USER_PREFIX + SaHolder.getRequest().getHeader(ProjectConst.ID_TOKEN);
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            return (User) redisTemplate.opsForValue().get(key);
        }else {
            throw new CustomException(CodeConst.TOKEN_FAIL_OR_EXPIRE);
        }
    }


    /**
     * 移除用户
     * @param user
     */
    public  void removeUser(User user) {
        String key = ProjectConst.USER_PREFIX + SaHolder.getRequest().getHeader(ProjectConst.ID_TOKEN);
        if (redisUserUtil.hasUserKey(key)) {
            redisUserUtil.deleteUser(key);
        }

    }

    public  void initRemoveUser(User user) {
        String key = ProjectConst.USER_PREFIX + user.getUserId();
        if (redisUserUtil.hasUserKey(key)) {
            redisUserUtil.deleteUser(key);
        }
    }

}
